package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@RequiredArgsConstructor

public class DishController {
    private final DishService dishService;

    private final RedisTemplate redisTemplate;

    //新增菜品
    @PostMapping
    @ApiOperation("新增菜品信息")
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品：{}",dishDTO);
        dishService.save(dishDTO);

        String key = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(key);

        return Result.success();
    }


    //分页查询菜品信息
    @GetMapping("/page")
    @ApiOperation("分页查询菜品信息")
    public Result query(DishPageQueryDTO dishPageQueryDTO){
        PageResult pageResult = dishService.query(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    //批量删除菜品信息
    @DeleteMapping
    @ApiOperation("批量删除菜品信息")
    public Result deleteByIds(@RequestParam List<Long> ids){
        dishService.deleteByIds(ids);

        //删除所有dish_缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);


        return Result.success();
    }

    //修改菜品
    //1、根据id查询菜品(查询回显)
    @GetMapping("/{id}")
    @ApiOperation("查询回显菜品信息")
    public Result<DishVO> queryById(@PathVariable Long id){
        DishVO dishVO = dishService.getById(id);
        return Result.success(dishVO);
    }

    //2、修改菜品
    @PutMapping
    @ApiOperation("修改菜品信息")
    public Result update(@RequestBody DishDTO dishDTO){
        dishService.update(dishDTO);

        //删除所有dish_缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> list(Long categoryId){
        List<Dish> list = dishService.getByCategoryId(categoryId);
        return Result.success(list);
    }

    //修改菜品起售停售
    @PostMapping("/status/{status}")
    @ApiOperation("修改菜品起售停售")
    public Result setStatus(@PathVariable Integer status,Long id){
        dishService.setStatus(status,id);

        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return Result.success();
    }




}
